package com.jic.market.impl.rest.discount.processor;

import com.alibaba.fastjson.JSONObject;
import com.beust.jcommander.internal.Lists;
import com.jic.common.base.vo.AdminOperate;
import com.jic.member.api.rest.EventListenerProviderApi;
import com.jic.member.constant.enums.EventTypeEnums;
import com.jic.member.request.EventListenerInputDTO;
import com.jic.market.common.exception.MarketErrorCodeEnum;
import com.jic.market.common.exception.MarketException;
import com.jic.market.common.util.Money;
import com.jic.market.entity.coupon.CouponConfig;
import com.jic.market.entity.coupon.CouponDetail;
import com.jic.market.enums.DiscountAmountServiceOperateEnum;
import com.jic.market.impl.rest.discount.model.ConditionDiscountModel;
import com.jic.market.impl.rest.discount.model.GoodsDetailModel;
import com.jic.market.mapper.coupon.CouponConfigMapper;
import com.jic.market.mapper.coupon.CouponDetailMapper;
import com.jic.market.request.rest.discount.DiscountBaseRequest;
import com.jic.market.request.rest.discount.DiscountOrderCreateRequest;
import com.jic.market.response.rest.coupon.QueryCouponPersonResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author yinhaijun
 * @date: 2020/4/27
 */
@Service("CouponDiscountProcessor")
public class CouponDiscountProcessor extends AbstractConditionDiscountProcessor {
    @Resource
    private EventListenerProviderApi eventListenerProviderService;
    @Autowired
    private CouponConfigMapper couponConfigMapper;
    @Autowired
    private CouponDetailMapper couponDetailMapper;

    @Override
    public ConditionResult isCondition(ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request, DiscountAmountServiceOperateEnum operate) {
//        if(!checkPromotion(((DiscountBaseRequest)request).getThirdUserId(), ((DiscountBaseRequest)request).getAdminOperate().getChildId().toString(), conditionDiscountModel.getChannelCodes(), conditionDiscountModel.getPromotionMemberGradeList())){
//            return new ConditionResult(false, "优惠劵计算"+conditionDiscountModel.getPromotionCode()+"会员等级校验未通过");
//        }
        QueryCouponPersonResponse couponInfo = conditionDiscountModel.getCouponInfo();
        if(null == couponInfo){
            throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, "此活动没有优惠劵");
        }

        CouponConfig couponConfig = couponConfigMapper.queryByPromotionId(conditionDiscountModel.getPromotionId());
        if(null == couponConfig || null == couponConfig.getCouponAmount()){
            throw new MarketException(MarketErrorCodeEnum.SYS_ERROR, "此优惠劵活动没有基础配置");
        }

        // 计算优惠劵对应涉及到的商品总价
        List<String> thirdSkuIdList = conditionDiscountModel.getThirdSkuIdList();
        if(null == thirdSkuIdList || thirdSkuIdList.isEmpty()){
            return new ConditionResult(false, "没有对应商品");
        }
        BigDecimal conditionTotalAmount = conditionDiscountModel.getActualTotalAmount(goodsDetailModelMap);

        // 未达到使用优惠劵的金额
        if(conditionTotalAmount.compareTo(couponConfig.getUseTotalAmountLimit()) == -1){
            return new ConditionResult(false, "未满足使用条件");
        }
        ConditionResult conditionResult = new ConditionResult(true, "通过");
        conditionResult.setConditionTotalAmount(conditionTotalAmount);
        conditionResult.setObject(couponConfig);
        return conditionResult;
    }

    @Override
    public void querySettlementAfter(ConditionResult conditionResult, ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request) {
        CouponConfig couponConfig = (CouponConfig) conditionResult.getObject();
        // 涉及到的商品的总金额
        BigDecimal totalAmount = conditionResult.getConditionTotalAmount();
        // 0是金额劵
        if (couponConfig.getCouponMode().equals(0)) {
            if (conditionDiscountModel.getCouponInfo().getAmountDeductType().equals(0)
                    || conditionDiscountModel.getCouponInfo().getAmountDeductType().equals(2)) {
                conditionDiscountModel.setPromotionDiscountTotalAmount(couponConfig.getCouponAmount());
            } else if (conditionDiscountModel.getCouponInfo().getAmountDeductType().equals(1)) {
                conditionDiscountModel.setPromotionDiscountFreightAmount(couponConfig.getCouponAmount());
            }
        } else {
            // 1是折扣劵
            BigDecimal youhuizhekou = Money.divide(Money.subtract(new BigDecimal(10), couponConfig.getCouponAmount()), new BigDecimal(10));
            if (conditionDiscountModel.getCouponInfo().getAmountDeductType().equals(0)
                    || conditionDiscountModel.getCouponInfo().getAmountDeductType().equals(2)) {
                conditionDiscountModel.setPromotionDiscountTotalAmount(Money.multiply(totalAmount, youhuizhekou));
            } else if (conditionDiscountModel.getCouponInfo().getAmountDeductType().equals(1)) {
                conditionDiscountModel.setPromotionDiscountFreightAmount(Money.multiply(totalAmount, youhuizhekou));
            }
        }

    }

    @Override
    public void createAfter(ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request) {
        String couponCode = conditionDiscountModel.getCouponInfo().getCouponCode();
        // 使用当前优惠劵
        CouponDetail couponDetailQ = new CouponDetail();
        couponDetailQ.setCouponCode(conditionDiscountModel.getCouponInfo().getCouponCode());
        List<CouponDetail> couponDetailList= couponDetailMapper.query(couponDetailQ);
        if(null == couponDetailList || couponDetailList.isEmpty()){
            throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, couponCode + "优惠券不存在");
        }else {
            if(!couponDetailList.get(0).getStatus().equals("1")){
//                throw new MarketException(MarketErrorCodeEnum.PARAM_ERROR, couponCode + "优惠券不能使用");
            }
        }
        List<String> couponCodeList = new ArrayList<>();
        couponCodeList.add(conditionDiscountModel.getCouponInfo().getCouponCode());
        long flag = couponDetailMapper.updateStatus(couponCodeList, 2);//已使用
        // 使用过后，发送给自动化营销系统
        if(flag == 1){
            DiscountOrderCreateRequest requestUser = (DiscountOrderCreateRequest) request;
            AdminOperate adminOperate = requestUser.getAdminOperate();
            Integer deptType = 1;
            List<Long> deptIds = Lists.newArrayList(101L,102L);
            if(null != adminOperate){
                deptType = adminOperate.getDeptType().getCode();
                deptIds = adminOperate.getDeptIds();
            }
            JSONObject param = new JSONObject();
            // 当前优惠券的优惠金额
            param.put("promCode",conditionDiscountModel.getCouponInfo().getPromotionId());//优惠券的活动id在coupInfo里
            param.put("verificationChannels",null);
            eventListenerProviderService.processEvent(
                    new EventListenerInputDTO()
                            .setEventCode("coupons_verification")
                            .setEventType(EventTypeEnums.CONSUME_EVENT_TYPE.getType())
                            .setDeptType(deptType)
                            .setDeptIds(deptIds)
                            .setEventTime(System.currentTimeMillis())
                            .setThirdUserId(requestUser.getThirdUserId())
                            .setParam(param)
            );
        }
    }


    @Override
    public void isAllCancelAfter(ConditionDiscountModel conditionDiscountModel, Map<String, GoodsDetailModel> goodsDetailModelMap, Object request) {
        // 退还当前优惠劵
        List<String> couponCodeList = new ArrayList<>();
        couponCodeList.add(conditionDiscountModel.getCouponInfo().getCouponCode());
        long flag = couponDetailMapper.updateStatus(couponCodeList, 1);//未使用
    }

}
